//
// Created by 朱宗辉 on 2023/3/14.
//
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 20

typedef struct {
    int no;
    int score;
} Stu;

typedef struct {
    Stu *base; // 栈底指针
    Stu *top; // 栈顶指针
    int stackSize; // 当前已分配的全部存储空间
} SqStack;

void initStack(SqStack &sqStack);

void push(SqStack &sqStack, Stu &stu);

Stu *pop(SqStack &sqStack);

Stu *getTop(SqStack &sqStack);

int stackLength(SqStack &sqStack);

void initValue(SqStack &sqStack);

void show(SqStack &sqStack);

int main() {
    //定义一个栈
    //将十个同学信息入栈
    //打印栈的长度
    //输出所有数据
    SqStack sqStack;
    initStack(sqStack);
    initValue(sqStack);
    printf("stack length is: %d\n", stackLength(sqStack));
    show(sqStack);

    //出栈一个数据元素，并将这个数据元素打印出来
    //打印栈的长度
    //输出所有数据
    Stu *s1 = pop(sqStack);
    printf("the pop stu, no is %d, score is %d\n", s1->no, s1->score);
    printf("stack length is: %d\n", stackLength(sqStack));
    show(sqStack);

    //入栈一个数据元素（自己学号-1）同学
    //打印栈的长度
    //输出所有数据
    Stu s2 = {42, 1};
    push(sqStack, s2);
    printf("stack length is: %d\n", stackLength(sqStack));
    show(sqStack);

    //读出栈顶元素的值
    //打印栈的长度
    //输出所有数据
    Stu *s3 = getTop(sqStack);
    printf("the getTop stu, no is %d, score is %d\n", s3->no, s3->score);
    printf("stack length is: %d\n", stackLength(sqStack));
    show(sqStack);
    return 0;
}

// 初始化栈
void initStack(SqStack &sqStack) {
    sqStack.base = new Stu[MAXSIZE];
    sqStack.top = sqStack.base;
    sqStack.stackSize = MAXSIZE;
}

void push(SqStack &sqStack, Stu &stu) {
    if (sqStack.top - sqStack.base < sqStack.stackSize) {
        *sqStack.top = stu;
        sqStack.top++;
    } else {
        printf("栈已满");
    }
}

Stu *pop(SqStack &sqStack) {
    if (sqStack.top != sqStack.base) {
        sqStack.top--;
        return sqStack.top;
    } else {
        printf("栈为空");
        return NULL;
    }
}

Stu *getTop(SqStack &sqStack) {
    if (sqStack.top != sqStack.base) {
        return (sqStack.top - 1);
    } else {
        printf("栈为空");
        return NULL;
    }
}

int stackLength(SqStack &sqStack) {
    return sqStack.top - sqStack.base;
}

void initValue(SqStack &sqStack) {
    for (int i = 0; i < 10; ++i) {
        Stu stu;
        stu.no = i + 43;
        stu.score = 100 - i * 10;
        push(sqStack, stu);
    }
}

void show(SqStack &sqStack) {
    int length = stackLength(sqStack);
    for (int i = 0; i < length; ++i) {
        printf("the %d stu, no id %d, score is %d\n", i + 1, (sqStack.base + i)->no, (sqStack.base + i)->score);
    }
}
